package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.uduemc.biso.node.core.entities.SArticleSlug;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.ArticleService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteArticleSlugIdExist;

public class CurrentSiteArticleSlugIdExistValid implements ConstraintValidator<CurrentSiteArticleSlugIdExist, Long> {

	@Override
	public void initialize(CurrentSiteArticleSlugIdExist constraintAnnotation) {

	}

	@Override
	public boolean isValid(Long value, ConstraintValidatorContext context) {
		if (value == null) {
			return true;
		}
		if (value < 1) {
			return true;
		}
		RequestHolder requestHolder = SpringContextUtils.getBean("requestHolder", RequestHolder.class);
		ArticleService ArticleServiceImpl = SpringContextUtils.getBean("articleServiceImpl", ArticleService.class);
		SArticleSlug sArticleSlug = null;
		try {
			sArticleSlug = ArticleServiceImpl.findCurrentSlugById(value);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sArticleSlug == null) {
			return false;
		}

		if (sArticleSlug.getHostId().longValue() != requestHolder.getHost().getId().longValue()
				|| sArticleSlug.getSiteId().longValue() != requestHolder.getCurrentSite().getId().longValue()) {
			return false;
		}
		return true;
	}

}
